<template>
  <a-modal title="选择人群" v-model:visible="visible" width="1100px" @ok="save" @cancel="hide">
    <AccountTemplate @update:active="accountChange">
      <template #default>
        <div class="select-crowd-container">
          <a-button @click="refreshConversionList" style="margin-bottom: 10px">
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
          <div v-if="loading" class="loading-container">
            <a-spin />
          </div>
          <Crowd
            v-else
            :key="key"
            :columns="crowdColumns"
            :crowdList="crowdList"
            v-model:audience="audienceMap[accountId]"
            fieldName="tagName"
          />
        </div>
      </template>
    </AccountTemplate>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, provide, computed, onMounted } from "vue";
import AccountTemplate from "@/pages/NewBatchCreateAd/components/common/MultiAccountTemplate.vue";
import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";
import { queryAudienceList } from "@/api/adx-tool";
import { crowdColumns } from "@/pages/NewBatchCreateAd/adx/xiaomi/enum";
import _ from "lodash";
import Crowd from "@/pages/NewBatchCreateAd/components/crowd/index.vue";
const store = batchCreateAdStore();
const visible = ref(false);
const loading = ref(false);

const accountIdIndex = ref(0);

const { AccountItems } = store;
provide("accounts", AccountItems);

const key = ref(0);

// 计算账号id
const accountId = computed(() => {
  return AccountItems && AccountItems.length > 0 ? AccountItems[accountIdIndex.value]?._id : undefined;
});
const accountChange = (index: number) => {
  accountIdIndex.value = index;
  key.value++;
  requestData();
};

// 使用map保存列表数据
const accountCrowdMap: any = ref(new Map());

// 计算人群列表
const crowdList = computed(() => {
  return accountCrowdMap.value.get(accountId.value);
});

// 保存账号已选人群包 {账号id: {人群包}}
const obj = store.Campaign && store.Campaign.audienceMap ? store.Campaign.audienceMap : {};

const audienceMap: any = ref(_.cloneDeep(obj));

// 判断obj和账号的id是否对应，不对应则删除该key
Object.keys(obj).forEach((key: any) => {
  if (!AccountItems.some((account: any) => account._id == key)) {
    delete audienceMap.value[key];
  }
});

// 循环账号，先判断是否有人群包数据，没有则给所有账号的人群包数据设置默认值
AccountItems.forEach((account: any) => {
  if (!audienceMap.value[account._id]) {
    audienceMap.value[account._id] = { incude: [], exclude: [] };
  }
});

const requestData = () => {
  if (!accountCrowdMap.value.has(accountId.value)) {
    loading.value = true;
    queryAudienceList({ accountId: accountId.value })
      .then((res) => {
        accountCrowdMap.value.set(accountId.value, res);
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false;
      });
  }
};
// 刷新人群包
const refreshConversionList = () => {
  if (!accountId.value) return;
  // 重新加载当前账号的转化追踪列表
  accountCrowdMap.value.delete(accountId.value);
  requestData();
};

onMounted(() => {
  requestData();
});

const save = () => {
  store.Campaign.audienceMap = audienceMap.value;
  emit("update:hide");
};
// 导出给父组件使用的方法
const show = () => {
  visible.value = true;
};

const emit = defineEmits(["update:hide"]);
const hide = () => {
  emit("update:hide");
};

defineExpose({
  show,
});
</script>

<style scoped lang="less">
.select-crowd-container{
  width: 800px;
  height: 100%;
  .loading-container {
    flex: 1;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
